<?php

/**
 * 客户端并发请求中心
 */
namespace App\Service\HttpServer;
use App\Service\BaseService;
use App\Service\Code\Normal;
use Hyperf\Utils\WaitGroup;

class HttpConcurrenceRequestService extends BaseService
{
    /**
     * header请求头处理
     * @var array
     */
    protected $header = 
    [
        'json'              => 'postJsonCurl',
        'form-urlencoded'   => 'postFormUrlEncodedCurl',
        'form-data'         => 'postFormDataCurl'
    ];
    
    /**
     * 多数据并发请求
     * @param array $param
     */
    public function addMultiRequest( array $param)
    {
        if( empty($param['url']) ) {
            return Normal::returnCode(Normal::FAIL,"请求主参数url缺失");
        }
        
        if( empty($param['content_type']) ) {
            return Normal::returnCode(Normal::FAIL,"请求主参数content_type缺失");
        }
        
        if( empty($param['dataList']) ) {
            return Normal::returnCode(Normal::FAIL,"请求主参数dataList不能为空");
        }

        //开启协程处理
        $dataList       = $param['dataList'];
        $content_type   = $param['content_type'];
        $url            = $param['url'];
        
        if( empty($this->header[$content_type]) ) {
            return Normal::returnCode(Normal::FAIL,"请求主参数content_type:{$content_type}为实现方法!");
        }
        
        try 
        {
            $callMethod = $this->header[$content_type];
            $count = count($dataList);
            $co = new WaitGroup();
            $co->add($count);
            $_all_result = [];
            foreach ($dataList as $item)
            {
                co(function () use ($co,$item,$url,$callMethod,&$_all_result)
                {
                    $start = microtime(true);
                    $result = Http::{$callMethod}($url,$item);
                    $_all_result[] = [
                        'request'   => $item,
                        'response'  => $result,
                        'usedtime'  => bcsub((string)microtime(true),(string)$start,3)
                    ];
                    $co->done();
                });
            }
            $co->wait();
            return Normal::returnCode(Normal::SUC,"请求处理完成",$_all_result);
        } 
        catch ( \Throwable $th )
        {
            return Normal::returnCode(Normal::FAIL,"请求发生异常:{$th->getMessage()},{$th->getFile()},{$th->getLine()}");
        }
    }
}